package com.jwgf.Half485.modbusthreadpool;

import java.nio.ByteBuffer;

public class ModbusTCPUtils {

	public static final byte READ_REGISTER = 0x03;
	public static final byte WRITE_REGISTER = 0x10;

	public static short getPid(byte[] request) {
		ByteBuffer buffer = ByteBuffer.wrap(request, 0, 6);
		return buffer.getShort(2);
	}

	public static short getLen(byte[] request) {
		ByteBuffer buffer = ByteBuffer.wrap(request, 0, 6);
		return buffer.getShort(4);
	}

	public static byte getFunctionCode(byte[] request) {
		return request[7];
	}

	public static int getStartAddr(byte[] request) {
		ByteBuffer buffer = ByteBuffer.wrap(request, 0, 12);
		return buffer.getShort(8);
	}

	public static short getLoadLen(byte[] request) {
		ByteBuffer buffer = ByteBuffer.wrap(request, 0, 12);
		return buffer.getShort(10);
	}

	public static byte checkCmdType(byte[] cmd) {
		return cmd[7];
	}

	public static byte[] createReadRegisterCmd(byte id, int addr, int len) {
		byte[] cmd = new byte[12];
		// sequence num
		cmd[0] = 0;
		cmd[1] = 0;
		// pid
		cmd[2] = 0;
		cmd[3] = 0;
		// cmd len
		cmd[4] = 0;
		cmd[5] = 6;
		cmd[6] = id;
		cmd[7] = READ_REGISTER;
		cmd[8] = (byte) ((addr >> 8) & 0xff);
		cmd[9] = (byte) (addr & 0xff);
		cmd[10] = (byte) ((len >> 8) & 0xff);
		cmd[11] = (byte) (len & 0xff);
		return cmd;
	}

	public static byte[] createWriteRegisterCmd(byte id, int addr, byte[] data) {
		if (data != null && data.length % 2 == 0) {
			byte[] cmd = new byte[6 + 7 + data.length];
			// sequence num
			cmd[0] = 0;
			cmd[1] = 0;
			// pid
			cmd[2] = 0;
			cmd[3] = 0;
			// cmd len
			cmd[4] = 0;
			cmd[5] = (byte) (7 + data.length);
			cmd[6] = id;
			cmd[7] = WRITE_REGISTER;
			cmd[8] = (byte) ((addr >> 8) & 0xff);
			cmd[9] = (byte) (addr & 0xff);
			int len = data.length / 2;
			cmd[10] = (byte) ((len >> 8) & 0xff);
			cmd[11] = (byte) (len & 0xff);
			cmd[12] = (byte) data.length;
			System.arraycopy(data, 0, cmd, 13, data.length);

			return cmd;
		} else {
			return null;
		}
	}
}
